package com.ch.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ch.web.entity.XyDzEntity;
import com.ch.web.mapper.XyDzDao;
import com.ch.web.redis.UserMapCache;
import com.ch.web.service.XyDzService;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.Query;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("xyDzService")
public class XyDzServiceImpl extends ServiceImpl<XyDzDao, XyDzEntity> implements XyDzService {

    @Autowired
    UserMapCache userMapCache;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<XyDzEntity> page = this.page(
                new Query<XyDzEntity>().getPage(params),
                new QueryWrapper<XyDzEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean getIsDZ(Long talkId, Long currentUserId) {
        QueryWrapper<XyDzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("talk_id", talkId).eq("user_id", currentUserId);
        return ObjectUtils.isNotEmpty(this.getOne(wrapper));

    }

    @Override
    public boolean dzTalk(XyDzEntity xyDzEntity, HttpServletRequest request) {
        Long userIdByToken = userMapCache.getUserIdByToken(request);
        xyDzEntity.setUserId(userIdByToken);
        return this.save(xyDzEntity);

    }

    @Override
    public boolean cancelDz(XyDzEntity xyDzEntity, HttpServletRequest request) {
        QueryWrapper<XyDzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("talk_id", xyDzEntity.getTalkId()).eq("user_id", userMapCache.getUserIdByToken(request));
        return this.remove(wrapper);
    }

    @Override
    public List<Long> getDzUserIds(Long talkId) {
        QueryWrapper<XyDzEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("talk_id", talkId);
        return this.list(wrapper).parallelStream().map(XyDzEntity::getUserId).collect(Collectors.toList());
    }


}